package com.xiashuxia.wozhang;

import java.text.SimpleDateFormat;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.xiashuxia.wozhang.utils.AccessTokenKeeper;
import com.xiashuxia.wozhang.utils.Constants;

public class MainActivity extends ActionBarActivity implements
		WeiboAuthListener {
	public static final String TAG = "Main Activity";
	
	private Button mLoginButton;
	private TextView mLoginInfoTextView;
	
	private SsoHandler mSsoHandler;
	private AuthInfo mAuthInfo;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mLoginButton = (Button) findViewById(R.id.login_button);
		mLoginInfoTextView = (TextView) findViewById(R.id.textView);
		 
		mAuthInfo = new AuthInfo(this, Constants.APP_KEY,
				Constants.REDIRECT_URL, Constants.SCOPE);
	}
	
	public void loginWebOnly(View v) {
		if (mSsoHandler == null) {
			mSsoHandler = new SsoHandler(this, mAuthInfo);
		}
		mSsoHandler.authorizeWeb(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (mSsoHandler != null) {
			mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	@Override
	public void onCancel() {
		Log.d(TAG, "user canceled");
	}

	@Override
	public void onComplete(Bundle values) {
		Oauth2AccessToken accessToken = Oauth2AccessToken.parseAccessToken(values);
		if (accessToken != null && accessToken.isSessionValid()) {
			String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(
                    new java.util.Date(accessToken.getExpiresTime()));
			mLoginInfoTextView.setText(accessToken.getUid() + ":" + date);
			AccessTokenKeeper.writeAccessToken(getApplicationContext(), accessToken);
		}
	}

	@Override
	public void onWeiboException(WeiboException arg0) {
		Log.d(TAG, "WeiboException:" + arg0.getMessage());
	}
}
